<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "user_material".
 *
 * @property integer $id
 * @property integer $material_id
 * @property integer $user_id
 * @property double $storage_num
 * @property string $create_at
 * @property string $update_at
 *
 * @property User $user
 * @property Material $material
 */
class UserMaterial extends \app\models\BaseModel {
    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'user_material';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['material_id', 'user_id', 'storage_num'], 'required'],
            [['material_id', 'user_id'], 'integer'],
            [['storage_num'], 'number'],
            [['create_at', 'update_at'], 'safe'],
            [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
            [['material_id'], 'exist', 'skipOnError' => true, 'targetClass' => Material::className(), 'targetAttribute' => ['material_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => '原料库存ID',
            'material_id' => '原料ID',
            'user_id' => '用户名',
            'storage_num' => '原料库存',
            'create_at' => '创建时间',
            'update_at' => '更新时间',
        ];
    }

    public function fields() {
        $fields = [
            'id',
            'material',
            'user',
            'storage_num',
        ];
        $fields = array_combine($fields, $fields);

        return $fields;
    }

    public function extraFields() {
        $fields = [
            'material_id',
            'user_id',
            'create_at',
            'update_at',
        ];
        $fields = array_combine($fields, $fields);
        return $fields;
    }

    public static function getByMaterial(Material $material, User $user) {
        $model = static::findOne([
            'user_id'=>$user->id,
            'material_id'=>$material->id,
        ]);
        if(!$model) {
            $model = new static();
            $model->user_id = $user->id;
            $model->material_id = $material->id;
            $model->storage_num = 0;
        }
        return $model;
    }

    public function getUser() {
        return $this->hasOne(User::className(), ['id' => 'user_id'])->inverseOf('userMaterials');
    }

    public function getMaterial() {
        return $this->hasOne(Material::className(), ['id' => 'material_id'])->inverseOf('userMaterials');
    }
}
